import 'package:private_journey/pages/widget_for_reader.dart';

// Using a type alias for clarity. A single clipboard "paste" can contain multiple items.
typedef ClipboardItem = List<ReaderInfo>;

/// Represents a single entry in the clipboard history.
class ClipboardHistoryEntry {
  final String md5;
  final ClipboardItem item;

  ClipboardHistoryEntry({required this.md5, required this.item});
}

/// Abstract repository for storing and retrieving clipboard history.
abstract class ClipboardHistoryRepository {
  /// Adds a new entry to the history.
  Future<void> add(ClipboardHistoryEntry entry);

  /// Retrieves all history entries, typically newest first.
  Future<List<ClipboardHistoryEntry>> getAll();

  /// Clears all entries from the history.
  Future<void> clear();
}

/// An in-memory implementation of the clipboard history repository.
class InMemoryClipboardHistoryRepository implements ClipboardHistoryRepository {
  final List<ClipboardHistoryEntry> _history = [];
  final int maxSize;

  InMemoryClipboardHistoryRepository({this.maxSize = 100});

  @override
  Future<void> add(ClipboardHistoryEntry entry) async {
    // Remove any existing entry with the same hash.
    _history.removeWhere((e) => e.md5 == entry.md5);

    // Add the new entry to the top.
    _history.insert(0, entry);

    // Trim the history if it exceeds the max size.
    if (_history.length > maxSize) {
      _history.removeLast();
    }
  }

  @override
  Future<List<ClipboardHistoryEntry>> getAll() async {
    return List.unmodifiable(_history);
  }

  @override
  Future<void> clear() async {
    _history.clear();
  }
}
